const {mysql} = require('../../qcloud')

//获取搜索历史（search/search.vue/getHotData 方法）
async function indexAction(ctx) {
	const {openId} = ctx.request.query
  const hotData = await mysql('nideshop_keywords').column('keyword').select()
	const historyData = await mysql('nideshop_search_history').where({
    	'user_id': openId
	}).select()
	ctx.state.data = {
	    'hotData': hotData,
	    'historyData': historyData
	  }
}

//添加搜索历史记录事件
// 添加搜索历史 （search/search.vue/searchWords 方法）
async function addHistoryAction(ctx) {
  const {openId, keyword} = ctx.request.body
  const oldData = await mysql('nideshop_search_history').where({
    'user_id': openId,
    'keyword': keyword
  })
  if (oldData.length == 0) {
    const insertData = await mysql('nideshop_search_history').insert({
      'user_id': openId,
      'keyword': keyword,
      'add_time': parseInt(new Date().getTime() / 1000)
    })
    if (insertData) {
      ctx.state= {
	  	data:'记录插入成功'
	  }
    } else {
      ctx.state = {
	  	data:'记录插入失败'
	  }
    }
  } else {
    ctx.state = {
      data: '已经有记录了'
    }
  }
}

// 清除历史记录 （search/search.vue/clearHistory 方法）
async function clearHistoryAction(ctx) {
  const openId = ctx.request.body.openId
  // console.log(openId)
  const data = await mysql('nideshop_search_history').where({
    'user_id': openId
  }).del()
  if (data) {
    ctx.state = {
      data: '清除成功'
    }
  } else {
    ctx.state = {
      data: '清除成功'
    }
  }
}

//点击搜索记录的某记录时进入商品列表显示信息

//搜索词实时获取数据库里的商品信息提示语（search/search.vue/tipsearch 方法）
async function helperAction(ctx) {
  const keyword = ctx.query.keyword
  var order = ctx.query.order
  console.log("======order=====:",order)
  if (!order) {
    order = ''
    orderBy = 'id'
  } else {
    orderBy = 'retail_price'
  }
  const keywords = await mysql('nideshop_goods').orderBy(orderBy, order)
  .column('id', 'name', 'list_pic_url', 'retail_price')
  .where('name', 'like', '%' + keyword + '%').limit(10).select()
  if (keywords) {
    ctx.state.data = {
      keywords
    }
  } else {
    ctx.state.data = {
      keywords: []
    }
  }
}

module.exports = {
	indexAction,
	addHistoryAction,
  clearHistoryAction,
  helperAction
}